package com.korion.android.devicedemon.base

import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

object JsonUtils {

    private const val TAG = "JsonUtils"
    private val gson = Gson()

    fun <T> fromJson(json: String?, clazz: Class<T>): T? {
        if (json == null) {
            return null
        }
        return try {
            gson.fromJson(json, clazz)
        } catch (e: Exception) {
            Log.e(TAG, "can't parse json: $json", e)
            null
        }
    }

    fun <T> fromJson(json: String?, typeToken: TypeToken<T>): T? {
        if (json == null) {
            return null
        }
        return try {
            gson.fromJson(json, typeToken)
        } catch (e: Exception) {
            Log.e(TAG, "can't parse json: $json", e)
            null
        }
    }

    fun toJson(obj: Any?): String? {
        if (obj == null) return null
        return gson.toJson(obj)
    }
}